#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEngine;

namespace OA
{
    public static class AddressableSerializationTrigger
    {
        // 示例：触发默认Addressable设置中所有Group的序列化
        public static void TriggerAllGroupsSerialization()
        {
            // 1. 获取原始设置文件路径
            var originalSettings = AddressableAssetSettingsDefaultObject.Settings;
            if (originalSettings == null)
            {
                EditorUtility.DisplayDialog("错误", "未找到Addressable设置", "确定");
                return;
            }

            string originalPath = AssetDatabase.GetAssetPath(originalSettings);
            if (string.IsNullOrEmpty(originalPath) || !File.Exists(originalPath))
            {
                EditorUtility.DisplayDialog("错误", $"设置文件不存在：{originalPath}", "确定");
                return;
            }

            // 2. 定义备份路径（项目临时目录）
            string backupDir = Path.Combine(Application.temporaryCachePath, "AddressableBackup");
            string backupPath = Path.Combine(backupDir, Path.GetFileName(originalPath));

            // 3. 确认操作
            bool confirm = EditorUtility.DisplayDialog(
                "确认操作",
                $"操作流程：\n1. 备份文件到 {backupDir}\n2. 删除原文件 {originalPath}\n3. 刷新资源\n4. 从备份恢复文件\n是否执行？",
                "执行", "取消");
            if (!confirm) return;

            try
            {
                // 确保备份目录存在
                Directory.CreateDirectory(backupDir);

                // 4. 备份文件（覆盖已有备份）
                File.Copy(originalPath, backupPath, overwrite: true);
                Debug.Log($"已备份设置文件：{backupPath}");

                // 5. 删除原文件
                AssetDatabase.DeleteAsset(originalPath);
                Debug.Log($"已删除原文件：{originalPath}");

                // 6. 刷新资源使删除生效
                AssetDatabase.Refresh();
                Debug.Log("资源刷新完成（删除生效）");

                // 7. 从备份恢复文件
                File.Copy(backupPath, originalPath, overwrite: true);
                Debug.Log($"已从备份恢复文件：{originalPath}");

                // 8. 再次刷新使恢复生效
                AssetDatabase.Refresh();
                Debug.Log("资源刷新完成（恢复生效）");

                // 9. 清理备份（可选，保留可用于手动恢复）
                // File.Delete(backupPath);

                EditorUtility.DisplayDialog("成功", "文件操作完成：删除并恢复成功", "确定");
            }
            catch (IOException ioEx)
            {
                EditorUtility.DisplayDialog("文件错误", $"文件操作失败：{ioEx.Message}", "确定");
                Debug.LogError($"IO异常：{ioEx}");
            }
            catch (System.Exception ex)
            {
                EditorUtility.DisplayDialog("错误", $"操作失败：{ex.Message}", "确定");
                Debug.LogError($"异常：{ex}");
            }
        }
    }
}

#endif